﻿/*----------------------------------------------------------------
  //Copyright (C) 2012 赵国伟
  //文件名：CategoriesManage.cs
  //文件功能描述：品牌管理
  //创建人：赵国伟
  //生成时间：2012/03/17 16:15:00
//----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Shopping.Common;
using Shopping.Model;
using Shopping.DAL;

namespace Shopping.BLL
{
    public class CategoriesManage
    {
        private readonly DALCategories dalCategory = new DALCategories();

        #region "返回指定状态的树形类别信息  by 赵国伟 2012-03-17"
        /// <summary>
        /// 返回指定状态的树形类别信息
        /// </summary>
        /// <param name="isAvailable">是否正用</param>
        /// <returns></returns>
        public List<Categories> GetTreeList(bool isAvailable)
        {
            string cond = " Status <> '" + Status.已删除.ToString()+"'";
            if (isAvailable)
                cond += " and Status='" + Status.正用.ToString()+"'";

            string orderBy = "Depth,ParentID";

            List<Categories> listOfCategories = dalCategory.QueryList(cond, orderBy); //该结果集 排序方式 必须按照ParentID 升序排列；
            if (listOfCategories == null)
                return null;

            //转化为Hash结构；
            Dictionary<int, Categories> dictCategories = new Dictionary<int, Categories>();
            for (int i = 0; i < listOfCategories.Count; ++i)
            {
                dictCategories.Add(listOfCategories[i].CategoryID, listOfCategories[i]);
            }

            SortedDictionary<double, Categories> dictOfResult = new SortedDictionary<double, Categories>();
            Dictionary<int, int> dictTreeItems = new Dictionary<int, int>(); //存储当前节点的子节点数；
            Dictionary<int, double> dictNodeOrders = new Dictionary<int, double>(); //当前节点的排序值；
            Dictionary<int, int> dictAppendCategories = new Dictionary<int, int>(); //记录被追加过的部门；
            Dictionary<int, int> dictTreeDepth = new Dictionary<int, int>();  //节点深度；
            Categories CategoriesInfo = null;
            double maxLevel = 8; //树形结构最大深度； 暂时设置了8级 该级已远足够目前使用；
            double originalNumber = Math.Pow(10, 2 * maxLevel);
            int cur = Convert.ToInt32(Math.Pow(10, maxLevel));
            dictTreeItems.Add(0, 0);
            for (int i = 0; i < listOfCategories.Count; ++i)
            {
                CategoriesInfo = listOfCategories[i];
                if (CategoriesInfo.ParentID == 0)
                {   //根节点的情况；
                    dictTreeItems.Add(CategoriesInfo.CategoryID, 0); //建立当前的节点的记录子节点数的值；
                    dictTreeItems[CategoriesInfo.ParentID]++; //更新父ID的子节点数；

                    CategoriesInfo.Depth = 1;
                    dictTreeDepth.Add(CategoriesInfo.CategoryID, 1);//存放当前节点的深度
                    double number = originalNumber + Math.Pow(10, 2 * (maxLevel - CategoriesInfo.Depth)) * dictTreeItems[0]; //计算当前节点的排序值；

                    dictNodeOrders.Add(CategoriesInfo.CategoryID, number); //记录当前节点排序值；
                    dictOfResult.Add(number, listOfCategories[i]);//将排序值与对应的节点信息保存在Hash表中；

                }
                else
                {
                    //子节点的情况；
                    if (dictTreeItems.ContainsKey(CategoriesInfo.ParentID))
                    {
                        dictTreeItems[CategoriesInfo.ParentID]++; //更新父ID的子节点数；
                        dictTreeItems.Add(CategoriesInfo.CategoryID, 0); //建立当前的节点的记录子节点数的值；

                        dictTreeDepth.Add(CategoriesInfo.CategoryID, dictTreeDepth[CategoriesInfo.ParentID] + 1); //存放当前节点的深度
                        CategoriesInfo.Depth = dictTreeDepth[CategoriesInfo.ParentID] + 1;

                        //排序队列；
                        double number = dictNodeOrders[CategoriesInfo.ParentID] + Math.Pow(10, 2 * (maxLevel - CategoriesInfo.Depth)) * dictTreeItems[CategoriesInfo.ParentID];

                        dictNodeOrders.Add(CategoriesInfo.CategoryID, number); //记录当前节点排序值；
                        dictOfResult.Add(number, listOfCategories[i]);//将排序值与对应的节点信息保存在Hash表中；
                    }
                    else
                    {
                        if (dictCategories.ContainsKey(CategoriesInfo.ParentID) && !dictAppendCategories.ContainsKey(CategoriesInfo.ParentID))
                        {
                            listOfCategories.Add(CategoriesInfo);
                            dictAppendCategories.Add(CategoriesInfo.ParentID, CategoriesInfo.ParentID);
                        }
                    }
                }

            }
            List<Categories> listOfTarget = new List<Categories>();
            foreach (KeyValuePair<double, Categories> item in dictOfResult)
            {
                listOfTarget.Add(item.Value);
            }
            return listOfTarget;


        }
        #endregion

        #region "查询指定状态的叶子节点(终结点)分类信息 by 赵国伟 2012-04-07"
        /// <summary>
        /// 查询指定状态的叶子节点(终结点)分类信息
        /// </summary>
        /// <param name="IsAvailable"></param>
        /// <returns></returns>
        public List<IDNameObj> QueryEndNodeCategories(bool IsAvailable)
        {
            CategoriesManage bllCategories = new CategoriesManage();
            List<Categories> listData = bllCategories.GetTreeList(IsAvailable);
            if (listData == null)
                return null;
            Dictionary<int, Categories> dictEndNodes = new Dictionary<int, Categories>();//存储终节点。
            for (int i = 0; i < listData.Count; ++i)
            {
                if ((i + 1) == listData.Count || listData[i].Depth >= listData[i + 1].Depth)
                    dictEndNodes.Add(listData[i].CategoryID, listData[i]);
            }

            //未终节点增加其父节点的名称；

            List<IDNameObj> listOfResult = new List<IDNameObj>();
            Dictionary<int, Categories> dictCategories = bllCategories.GetAllCategoriesToHash();
            foreach (KeyValuePair<int, Categories> endNode in dictEndNodes)
            {
                IDNameObj obj = new IDNameObj();
                obj.ID = endNode.Key;
                obj.Name = bllCategories.GetFullName(endNode.Value, dictCategories);
                listOfResult.Add(obj);
            }
            return listOfResult;
        }
        #endregion

        #region "返回指定类别的全根类别名称；（含父类信息) by 赵国伟 2012-04-07"
        /// <summary>
        /// 返回指定类别的全根类别名称；（含父类信息）
        /// </summary>
        /// <param name="c"></param>
        /// <param name="dictAllCategories"></param>
        /// <returns></returns>
        private string GetFullName(Categories c, Dictionary<int, Categories> dictAllCategories)
        {
            string result = c.CategoryName;
            if (c.ParentID > 0)
            {
                result = GetFullName(dictAllCategories[c.ParentID], dictAllCategories) + ">>" + result;
            }

            return result;
        }
        #endregion

        #region "获取指定的叶子节点类别信息；输出为复选框选项； by 赵国伟 2012-04-07"
        /// <summary>
        /// 获取指定的叶子节点类别信息；输出为复选框选项；
        /// </summary>
        /// <param name="IsAvailable"></param>
        /// <param name="chkObjectName"></param>
        /// <param name="defaultValue"></param>
        /// <param name="maxLineNumber"></param>
        /// <returns></returns>
        public static string GetEndNodeCategoriesToCheckOption(bool IsAvailable,string chkObjectName, string defaultValue, int maxLineNumber)
        {
            CategoriesManage bllCategory = new CategoriesManage();
            return BLLHelper.GenerateToCheckOption(bllCategory.QueryEndNodeCategories(IsAvailable), chkObjectName, defaultValue, maxLineNumber);
        }
        #endregion

        #region "获取指定的叶子节点类别信息；输出为下拉选项； by 赵国伟 2012-04-07"
        /// <summary>
        /// 获取指定的叶子节点类别信息；输出为下拉选项；
        /// </summary>
        /// <param name="IsAvailable"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static string GetEndNodeCategoriesToSelectOption(bool IsAvailable,string defaultValue)
        {
            CategoriesManage bllCategory = new CategoriesManage();
            return BLLHelper.GenerateToSelectOption(bllCategory.QueryEndNodeCategories(IsAvailable),  defaultValue);
        }
        #endregion

        #region "查询所有的类别信息，并输出为Hash结构对象； by 赵国伟 2012-04-07"
        /// <summary>
        /// 查询所有的类别信息，并输出为Hash结构对象；
        /// </summary>
        /// <returns></returns>
        public Dictionary<int, Categories> GetAllCategoriesToHash()
        {
            Dictionary<int, Categories> dict = new Dictionary<int, Categories>();
            List<Categories> listOfData = dalCategory.QueryList("", "");
            foreach(Categories c in listOfData)
                dict.Add(c.CategoryID, c);
            return dict;
        }
        #endregion


        #region "返回所有的类别信息并输出为下拉选项  by 赵国伟 2012-03-17"
        /// <summary>
        /// 返回所有的类别信息并输出为下拉选项
        /// </summary>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static string GetTreeListToddlOption(string defaultValue)
        {
            CategoriesManage bllCategories = new CategoriesManage();
            List<Categories> listData = bllCategories.GetTreeList(false);
            return GetTreeListToddlOption(listData, defaultValue);
        }
        #endregion

        #region "返回所有的类别信息并输出为下拉选项  by 赵国伟 2012-03-17"
        /// <summary>
        ///返回所有的类别信息并输出为下拉选项
        /// </summary>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static string GetTreeListToddlOption(List<Categories> listCategories, string defaultValue)
        {
            StringBuilder sb = new StringBuilder(500);
            if (listCategories != null)
            {
                foreach (Categories datainfo in listCategories)
                {
                    sb.Append("<option value=\"");
                    sb.Append(datainfo.CategoryID);
                    sb.Append("\" ");
                    if (defaultValue == datainfo.CategoryID.ToString())
                    {
                        sb.Append(" Selected ");
                    }
                    if (datainfo.Status != Status.正用.ToString())
                    {
                        sb.Append(" style=\"color:gray;\" ");
                    }

                    sb.Append(">");
                    for (int i = 1; i < datainfo.Depth; ++i)
                    {
                        sb.Append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
                    }
                    sb.Append(datainfo.CategoryName);
                    sb.Append("</option>");
                }
            }
            return sb.ToString();
        }
        #endregion

        #region "保存类别信息； by 赵国伟 2012-03-17"
        /// <summary>
        ///保存类别信息
        /// </summary>
        /// <param name="CategoriesInfo">类别信息</param>
        /// <returns></returns>
        public ReturnValue Save(Categories categoryInfo)
        {
            ReturnValue ret = new ReturnValue(ResultType.Fail);
            if (categoryInfo == null)
            {
                ret.Message = "类别信息不能为空！";
            }
            else
            {
                //判断下必要的值是否已录入；
                if (categoryInfo.ParentID > 0)
                {
                    Categories parentCategories = dalCategory.GetModel(categoryInfo.ParentID);
                    if (parentCategories == null)
                    {
                        ret.Message = "未找到父类信息！";
                        return ret;
                    }
                    categoryInfo.RootID = parentCategories.RootID;
                    categoryInfo.Depth = parentCategories.Depth + 1;
                }


                if (categoryInfo.CategoryID <= 0)
                {
                    #region "添加的情况"
                    if (dalCategory.QueryList(1, "CategoryName='" + categoryInfo.CategoryName + "' and Depth=" + categoryInfo.Depth + " and Status<>'"+Status.已删除.ToString()+"' ", "") != null)
                    {
                        ret.Message = "类别名称不能重复！";
                    }
                    else
                    {
                        categoryInfo.CreateDate = DateTime.Now;
                        if (dalCategory.Add(categoryInfo) > 0)
                        {
                            ret.Result = ResultType.Success;
                            ret.Message = "保存成功！";
                        }
                        else
                        {
                            ret.Message = "保存失败";
                        }
                    }
                    #endregion
                }
                else
                {
                    #region "修改的情况"

                    if (dalCategory.QueryList(1, "(CategoryName='" + categoryInfo.CategoryName + "' ) and Depth=" + categoryInfo.Depth + " and Status<>'"+Status.已删除.ToString()+"' and CategoryID <>" + categoryInfo.CategoryID + "", "") != null)
                    {
                        ret.Message = "类别名称不能重复！";
                    }
                    else
                    {
                        Categories o = dalCategory.GetModel(categoryInfo.CategoryID);
                        categoryInfo.CreateDate = o.CreateDate;
                        if (dalCategory.Update(categoryInfo) > 0)
                        {
                            ret.Result = ResultType.Success;
                            ret.Message = "保存成功！";
                        }
                        else
                        {
                            ret.Message = "保存失败";
                        }
                    }
                    #endregion
                }
            }

            return ret;
        }
        #endregion

        #region "查询指定类别的名称； by 赵国伟 2012-03-17"
        /// <summary>
        /// 查询指定类别的名称；
        /// </summary>
        /// <param name="CategoryID"></param>
        /// <returns></returns>
        public string GetCategoriesName(int CategoryID)
        {
            return DALHelper.GetFieldValue<Categories>(CategoryID, "CategoryName");
        }
        #endregion

        #region "查询一条类别信息 by 赵国伟 2012-03-18"
        /// <summary>
        /// 查询一条类别信息
        /// </summary>
        /// <param name="categoryId"></param>
        /// <returns></returns>
        public Categories GetCategoryInfo(int categoryId)
        {
            return dalCategory.GetModel(categoryId);
        }
        #endregion

        #region "删除指定的分类 by 赵国伟 2012-04-02"
        /// <summary>
        /// 删除指定的分类
        /// </summary>
        /// <param name="brandId"></param>
        /// <returns></returns>
        public ReturnValue Delete(int categoryId)
        {
            ReturnValue ret = new ReturnValue(ResultType.Fail, "删除失败！");
            if (dalCategory.QueryList(1, "ParentID='" + categoryId + "'", "") != null)
            {
                dalCategory.UpdateStatus(categoryId, Status.已删除.ToString());
                ret.Result = ResultType.Success;
                ret.Message = "删除成功！";
                return ret;
            }

            try
            {
                if (dalCategory.Delete(categoryId) > 0)
                {
                    ret.Result = ResultType.Success;
                    ret.Message = "删除成功！";
                }
            }
            catch
            {
                dalCategory.UpdateStatus(categoryId, Status.已删除.ToString());
                ret.Result = ResultType.Success;
                ret.Message = "删除成功！";
            }

            return ret;
        }
        #endregion


        #region "更新指定类别的状态； by 赵国伟 2012-03-18"
        /// <summary>
        /// 更新指定类别的状态；
        /// </summary>
        /// <param name="categoryId"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public int UpdateStatus(int categoryId, Status status)
        {
            return dalCategory.UpdateStatus(categoryId, status.ToString());
        }
        #endregion

        #region "查询指定类别的名称信息；并输出为Hash结构 by 赵国伟 2012-04-10"
        /// <summary>
        /// 查询指定类别的名称信息；并输出为Hash结构
        /// </summary>
        /// <param name="CategoryIds"></param>
        /// <returns></returns>
        public Dictionary<int, string> GetCategoryToHash(List<string> CategoryIds)
        {
            string cond = "";
            if (CategoryIds != null)
                cond = "CategoryID in('" + string.Join("','", CategoryIds.ToArray()) + "')";
            return BLLHelper.GenerateToHash(dalCategory.Find(cond,""));
        }
        #endregion

        #region 获取同级类别列表
        public List<Categories> GetBrotherByCategory(int categoryId, bool isAvailable)
        {
            var currentcat = dalCategory.GetModel(categoryId);
            if (currentcat == null)
                return null;
            string cond = " Status <> '" + Status.已删除.ToString() + "' and parentid=" + currentcat.ParentID;
            if (isAvailable)
                cond += " and Status='" + Status.正用.ToString() + "'";

            string orderBy = "Depth,ParentID";

            List<Categories> listOfCategories = dalCategory.QueryList(cond, orderBy); //该结果集 排序方式 必须按照ParentID 升序排列；
            return listOfCategories; 
        }
        #endregion

        #region "返回商品菜单（只支持到三级） by 赵国伟 2012-05-06"
        /// <summary>
        /// 返回商品菜单（只支持到三级）
        /// </summary>
        /// <returns></returns>
        public  List<CategoryMenu> GetCategoryMenu()
        {
            List<Categories> listOfData = GetTreeList(true);
            if (listOfData == null) return null;
            Dictionary<int, CategoryMenu> dict = new Dictionary<int, CategoryMenu>();
            Dictionary<int, int> dictS2F = new Dictionary<int, int>();
            for (int i = 0; i < listOfData.Count; ++i)
            {
                Categories c = listOfData[i];
                if (c.Depth == 1)
                {
                    dict.Add(c.CategoryID, new CategoryMenu());
                    dict[c.CategoryID].FCategory.ID = c.CategoryID;
                    dict[c.CategoryID].FCategory.Name = c.CategoryName;
                }
                else if (c.Depth == 2)
                {
                    IDNameObj d = new IDNameObj();
                    d.ID = c.CategoryID;
                    d.Name = c.CategoryName;
                    dict[c.ParentID].SCategorys.Add(d);
                    dictS2F.Add(c.CategoryID, c.ParentID);
                }
                else if (c.Depth == 3)
                {
                    int fid = dictS2F[c.ParentID];
                    IDNameObj d = new IDNameObj();
                    d.ID = c.CategoryID;
                    d.Name = c.CategoryName;
                    if (!dict[fid].TCategorys.ContainsKey(c.ParentID))
                        dict[fid].TCategorys.Add(c.ParentID, new List<IDNameObj>());
                    dict[fid].TCategorys[c.ParentID].Add(d);
                }
            }
            return Utility.HashToList<int, CategoryMenu>(dict);
        }

        #region "返回商品菜单（只支持到三级） by 赵国伟 2012-05-06"
        /// <summary>
        /// 返回商品菜单（只支持到三级）
        /// </summary>
        /// <returns></returns>
        public CategoryMenu GetCategoryMenu(int FCategoryID)
        {
            List<Categories> listOfData = GetTreeList(true);
            if (listOfData == null) return null;
            CategoryMenu menu = null;
            Dictionary<int, int> dictS2F = new Dictionary<int, int>();
            for (int i = 0; i < listOfData.Count; ++i)
            {
                Categories c = listOfData[i];
                if (c.Depth == 1 && c.CategoryID == FCategoryID)
                {
                    menu = new CategoryMenu();
                    menu.FCategory.ID = c.CategoryID;
                    menu.FCategory.Name = c.CategoryName;
                }
                else if (c.Depth == 2 && c.ParentID == FCategoryID)
                {
                    IDNameObj d = new IDNameObj();
                    d.ID = c.CategoryID;
                    d.Name = c.CategoryName;
                    menu.SCategorys.Add(d);
                    dictS2F.Add(c.CategoryID, c.ParentID);
                }
                else if (c.Depth == 3 && dictS2F.ContainsKey(c.ParentID))
                {
                    int fid = dictS2F[c.ParentID];
                    IDNameObj d = new IDNameObj();
                    d.ID = c.CategoryID;
                    d.Name = c.CategoryName;
                    if (!menu.TCategorys.ContainsKey(c.ParentID))
                        menu.TCategorys.Add(c.ParentID, new List<IDNameObj>());
                    menu.TCategorys[c.ParentID].Add(d);
                }
            }
            return menu;
        }
        #endregion
        #endregion


        #region "查询子类别信息； by 赵国伟 2012-05-12"
        /// <summary>
        /// 查询子类别信息；
        /// </summary>
        /// <param name="categoryId"></param>
        /// <param name="isAvailable"></param>
        /// <returns></returns>
        public List<Categories> QueryChirldCategory(int categoryId, bool isAvailable)
        {
             string cond = " Status <> '" + Status.已删除.ToString() + "' and parentid=" + categoryId;
             if (isAvailable)
                cond += " and Status='" + Status.正用.ToString() + "'";
             return dalCategory.QueryList(cond, "CreateDate asc");
        }
        #endregion

        #region "查询相关商品的类别； by 赵国伟 2012-05-22"
        /// <summary>
        /// 查询相关商品的类别；
        /// </summary>
        /// <param name="listOfGoodsIDs"></param>
        /// <returns></returns>
        public List<IDNameObj> QueryRelateCategory(List<string> listOfGoodsIDs)
        {
            string cond = "CategoryID in(Select CategoryID From Goods Where Status='" + Status.正用.ToString() + "' and SaleStatus='" + GoodsSaleStatus.已上架.ToString() + "')";
            cond += " and Status='" + Status.正用.ToString() + "' ";
            return dalCategory.Find(cond, "CategoryID desc");
        }
        #endregion

        #region "查询指定类别的所有父类信息 by 赵国伟  2012-09-01"
        /// <summary>
        /// 查询指定类别的所有父类信息；
        /// </summary>
        /// <param name="categoryId"></param>
        /// <returns></returns>
        public List<Categories> QueryTreeCategories(int categoryId)
        {
            List<Categories> list = null;
            Categories c = dalCategory.GetModel(categoryId);
            if (c != null)
            {
                list = new List<Categories>();
                list.Add(c);
            }

            if (c.Depth > 0)
            {
                list.AddRange(QueryTreeCategories(c.ParentID));
            }
            return list;
        }
        #endregion



    }
}
